package com.sq.partner.manager.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sq.partner.manager.dao.*;
import com.sq.partner.manager.mybatis.model.*;
import com.sq.partner.manager.service.*;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.Message;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.util.FreeMarkerUtil;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * @date 2015-11-02 新意健险产品配置
 */
@Controller
@RequestMapping("/nlifeProductConfig")
public class NlifeProductConfigController {
	private static Logger logger = LogUtil.getLog(NlifeProductConfigController.class);
	@Resource
	private INlifeProdDao nlifeProdDao;
	@Resource
	private INlifeProdConfigService nProductService;
	@Resource
	private INlifeCoreRiskDao nlifeCoreRiskDao;
	@Resource
	private ITradFeeAdjustConditionDao tradFeeAdjustConditionDao;
	@Resource
	private IGatewayChannelInfoConfigService gatewayChannelInfoConfigService;
	@Resource
	private INlifePlanDao nlifePlanDao;
	@Resource
	private FeeRateService feeRateService;
	/*@Resource
	private IGatewayClearCacheManager gatewayClearCacheManager;*/
	@Resource
	private TreddeFeeCovService tradeFeeCovService;
	@Resource
	private TradProdPropDao tradProdPropDao;
	@Resource
	private INlifeProdDao INlifeProdDao ;
	@Resource
	private INlifeCovDao iNlifeCovDao;
	@Resource
	private INlifeCoreProdDao nlifeCoreProdDao;

	@Resource
	private NlifeRationService nlifeRationService;

	@Resource
	private INlifeRiskDao nlifeRiskDao;

	@Resource
	private NlifeRiskService nlifeRiskService;
	@Resource
	INlifePlanConfigService iNlifePlanConfigService;
	@Resource
	private TradConfigService tradConfigService;
	private static DecimalFormat decimalFormat = new DecimalFormat("#.00");
	private  static BigDecimal percentHun = new BigDecimal(100);//百分比
	private  static BigDecimal conPropPercent= BigDecimal.valueOf(1.000000);//共保协议必须等于1


	@RequestMapping(value = "/list")
	public String list() throws Exception {
		logger.debug("forward newLifeProductConfig successful....");
		return "nlifeProduct/productConfig/list";
	}

	@RequestMapping(value = "/queryList")
	public @ResponseBody Page<NlifeProd> queryList(HttpServletRequest request,Integer size,Integer current,String prodCode,String prodName,String status,String startDate,String endDate) throws Exception{
		Page<NlifeProd> page=new Page<NlifeProd>();
		page.setCurrent(current);
		page.setSize(size);
		NlifeProd tradProdInst=new NlifeProd();
		tradProdInst.setProdCode(prodCode);
		tradProdInst.setProdName(prodName);
		tradProdInst.setStatus(status);
		tradProdInst.setVstartDate(startDate);
		tradProdInst.setVendDate(endDate);
		page.setType(tradProdInst);
		/**是否有导出权限判断*/
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		String userCodes=com.sq.partner.manager.common.Config.getProp("imple.nlife.userCodes");
		String[] codes=forProds(userCodes);
		boolean flag=false;
		logger.info("登录用户名："+user.getUserCode()+"   配置的用户名： "+userCodes);
		if(codes!=null&&codes.length>0){
			flag=Arrays.asList(codes).contains(user.getUserCode());
		}
		page.setObj(flag);
		return nProductService.queryProdPageByCriteria(page);
	}

	@RequestMapping(value = "/addReq")
	public String addReq(ModelMap model,HttpServletRequest request) throws Exception {
		loadPageDictData(model);
		List<DictDto>dics=DictCache.getDict(Constants.DICT_SPECIAL_INFO_TYPE);
		List<DictDto>epolicys=DictCache.getDict(Constants.DICT_EPOLICY_LIST);
		model.put("infoTypes", dics);
		model.put("epolicys", epolicys);
		return "nlifeProduct/productConfig/add";
	}

	//for common addReq  editReq
	private void loadPageDictData(ModelMap model) throws Exception {
		List<DictDto> agentTypeList = DictCache.getDict(Constants.DICT_AGENT_TYPE);
		List<DictDto> prodTypeList = DictCache.getProdType("3");
		List<DictDto> insurePeriodList = DictCache.getDict(Constants.DICT_NLIFE_INSURE_PERIOD);
		List<DictDto> polPoolType = DictCache.getDict(Constants.DICT_NEW_LIFE_POL_POOL_TYPE);
		model.put("agentTypeList", agentTypeList);
		model.put("prodTypeList", prodTypeList);
		model.put("insurePeriodList", insurePeriodList);
		model.put("polPoolType", polPoolType);
	}

	@RequestMapping(value = "/newLifeLoadTemplet")
	public @ResponseBody Page<NlifeCoreProd> loadTemplet(Integer size,Integer current,String coreProdCode,String coreProdName) throws Exception{
		Page<NlifeCoreProd> page=new Page<NlifeCoreProd>();
		page.setCurrent(current);
		page.setSize(size);
		//产品模板表
		NlifeCoreProd coreProdInst=new NlifeCoreProd();
		coreProdInst.setCoreProdCode(coreProdCode);
		coreProdInst.setCoreProdName(coreProdName);
		page.setType(coreProdInst);
		/*需要加载的字典表字段**/
		List<DictDto>  securityPlans=DictCache.getDict(Constants.DICT_SECURITY_PLAN);
		Map<String, Object>map=new HashMap<String, Object>();
		map.put("securityPlans", securityPlans);
		page.setObj(map);
		return nProductService.queryNLifeCoreProd(page);
	}

	@RequestMapping(value = "/saveNewLifeProd")
	public @ResponseBody Page<NlifeProd> saveNewLifeProduct(String prodName,
															String coreProdCode, String appType, String instant,
															Long maxDelayDay, Long minDelayDay, Long maxDays, Long minDays,
															String pppUnit, Long maxNumber, String prodType, String poolType,
															String ageLimit, Integer minAge, Integer maxAge,String minAgeUnit,String maxAgeUnit,
															String maxOccupLevel, String insuredNoLimit, Integer minInsuredNo,
															String agentType,String adjustStr,HttpServletRequest request,Long longestCancelDay,String special,
															String isSocial,String waitStage,String yearDeductible,BigDecimal payRate,String isSuppleCare,String epolicyCode,String epolicyTitle,String securityplan
			,String isCityIllness,String coPayRate,String minDelayUnit,String rations,String isRation,String premiumCheck,String isPjfee,BigDecimal pjfee,String planType,String riskMainType ,
															String continueMaxAge , String continueMaxAgeUnit,String claimLimit ,String graceStage,String isByStaged,String isInform,String isInternetClause
	) throws Exception{
		Page<NlifeProd> page =new Page<NlifeProd>();
		if(StrUtil.isEmpty(coreProdCode)){
			page.setMessage("产品模板代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(prodName)){
			page.setMessage("交易系统产品名称不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(poolType)){
			page.setMessage("共保选项不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(appType)){
			page.setMessage("交易系统投保类型不能为空");
			page.setResult("error");
			return page;
		}/*else if(StrUtil.isEmpty(prodType)){
			page.setMessage("产品类型不能为空");
			page.setResult("error");
			return page;
		}*/
		if(StrUtil.isEmpty(minDelayDay)){
			page.setMessage("最短延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*|-[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(minDelayDay.toString());
			if(!matcher.matches()){
				page.setMessage("最短延时起保天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(longestCancelDay)){
			page.setMessage("最长注销天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(longestCancelDay.toString());
			if(!matcher.matches()){
				page.setMessage("最长注销天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}

		if(StrUtil.isEmpty(maxDelayDay)){
			page.setMessage("最长延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*|-[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(maxDelayDay.toString());
			if(!matcher.matches()){
				page.setMessage("最长延时起保天数必须是整数");
				page.setResult("error");
				return page;
			}else{
				if(maxDelayDay<minDelayDay){
					page.setMessage("最长延时起保天数不能小于最短延时起保天数");
					page.setResult("error");
					return page;
				}
			}
		}
		if(StrUtil.isEmpty(minDays)){
			page.setMessage("最小保险期间不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(minDays.toString());
			if(!matcher.matches()){
				page.setMessage("最小保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(maxDays)){
			page.setMessage("最大保险期间不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(maxDays.toString());
			if(!matcher.matches()){
				page.setMessage("最大保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}else{
				if(maxDays<minDays){
					page.setMessage("最大保险期间不能小于最小保险期间");
					page.setResult("error");
					return page;
				}
			}
		}
		if(StrUtil.isEmpty(pppUnit)){
			page.setMessage("保险期间类型不能为空");
			page.setResult("error");
			return page;
		}/*else if(StrUtil.isEmpty(agentType)){
			page.setMessage("请选择销售类型");
			page.setResult("error");
			return page;
		}*/
		if(StrUtil.isEmpty(instant)){
			page.setMessage("即时投保限制不能为空");
			page.setResult("error");
			return page;
		}
		if(StrUtil.isEmpty(ageLimit)){
			page.setMessage("请选择投保年龄限制");
			page.setResult("error");
			return page;
		}
		if(StrUtil.isEmpty(insuredNoLimit)){
			page.setMessage("请选择最低投保人数限制");
			page.setResult("error");
			return page;
		}else{
			if("Y".equals(insuredNoLimit)){
				if(null==minInsuredNo){
					page.setMessage("请输入最低投保人数");
					page.setResult("error");
					return page;
				}else{
					if(minInsuredNo>99999||minInsuredNo<0){
						page.setMessage("最低投保人数为0-99999的有效整数");
						page.setResult("error");
						return page;
					}
				}
			}
		}
		if(StrUtil.isEmpty(maxNumber)){
			page.setMessage("最大份数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
			Matcher matcher = pattern.matcher(maxNumber.toString());
			if(!matcher.matches()){
				page.setMessage("最大份数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		//增加时间:2019/8/27,批减手续费选项(is_pjfee) Y是  N否,当选Y时显示一个输入框，可以输入0至1之间小数,
		//此输入框是批减扣除手续费比例(pjfee) 不输入时默认为0
		if("Y".equals(isPjfee) && pjfee != null) {
			String checkPjfee = pjfee.toString();
			Pattern pattern = Pattern.compile("^0\\.[0-9]*[1-9][0-9]*$");
			Matcher matcher = pattern.matcher(checkPjfee.toString());
			if(!"".equals(checkPjfee) && !"0".equals(checkPjfee) && !matcher.matches()){
				page.setMessage("批减扣除手续费必须是0至1之间小数");
				page.setResult("error");
				return page;
			}
		}
		//特殊产品标识 A2 广西学平险增加方案类型选项（A款 0000001，B款 0000002）
		if("1".equals(riskMainType) && "A2".equals(special) && StrUtil.isEmpty(planType)) {
			page.setMessage("广西学平险增加方案类型选项不能为空");
			page.setResult("error");
			return page;
		}

		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		NlifeProd tradProdInst=new NlifeProd();
		tradProdInst.setProdName(prodName);
		tradProdInst.setCoreProdCode(coreProdCode);
		tradProdInst.setAppType(appType);
		tradProdInst.setInstant(instant);
		tradProdInst.setMaxDelayDay(maxDelayDay);
		tradProdInst.setMinDelayDay(minDelayDay);
		tradProdInst.setMaxDays(maxDays);
		tradProdInst.setMinDays(minDays);
		tradProdInst.setPppUnit(pppUnit);
		tradProdInst.setMaxNumber(maxNumber);
		tradProdInst.setStartDate(new Date());
		tradProdInst.setStatus("0");
		tradProdInst.setProdType(prodType);
		tradProdInst.setPoolType(poolType);
		tradProdInst.setAgeLimit(ageLimit);
		tradProdInst.setMaxAge(maxAge);
		tradProdInst.setMinAge(minAge);
		tradProdInst.setMaxAgeUnit(maxAgeUnit);
		tradProdInst.setMinAgeUnit(minAgeUnit);
		tradProdInst.setMaxOccupLevel(maxOccupLevel);
		tradProdInst.setInsuredNoLimit(insuredNoLimit);
		tradProdInst.setMinInsuredNo(minInsuredNo);
		/*		tradProdInst.setAgentType(agentType);
		 */		tradProdInst.setAdjustStr(adjustStr);
		tradProdInst.setOprateCode(user.getUserCode());
		tradProdInst.setLongestCancelDay(longestCancelDay);
		tradProdInst.setSpecial(special);
		tradProdInst.setIsSocial(isSocial);
		tradProdInst.setWaitStage(waitStage);
		tradProdInst.setYearDeductible(yearDeductible);
		tradProdInst.setPayRate(payRate);
		tradProdInst.setIsSuppleCare(isSuppleCare);
		tradProdInst.setEpolicyCode(epolicyCode);
		tradProdInst.setEpolicyTitle(epolicyTitle);
		tradProdInst.setSecurityplan(securityplan);
		tradProdInst.setIsCityIllness(isCityIllness);
		tradProdInst.setCoPayRate(coPayRate);
		tradProdInst.setRation(rations);
		tradProdInst.setMinDelayUnit(minDelayUnit);
		tradProdInst.setIsRation(isRation);
		tradProdInst.setIsPjfee(isPjfee);
		tradProdInst.setPjfee(pjfee);
		tradProdInst.setPlanType(planType);
		tradProdInst.setClaimLimit(claimLimit);
		tradProdInst.setGraceStage(graceStage);
		tradProdInst.setRiskMainType(riskMainType);
		tradProdInst.setIsByStaged(isByStaged);
		tradProdInst.setIsInform(isInform);
		tradProdInst.setIsInternetClause(isInternetClause);
		if(continueMaxAge != null && continueMaxAgeUnit != null){
			tradProdInst.setContinueMaxAge(continueMaxAge);
			tradProdInst.setContinueMaxAgeUnit(continueMaxAgeUnit);
		}
		if(StrUtil.isNotEmpty(premiumCheck)){
			tradProdInst.setPremiumCheck(premiumCheck);
		}
		//目的得到添加产品编号便与险种配置
		page.setType(nProductService.saveProd(tradProdInst));
		return page;
	}
	@RequestMapping(value = "/editNewLifeRequst")
	public String editNewLifeRequst(ModelMap model,String prodCode) throws Exception {
		if(StrUtil.isEmpty(prodCode)){
			model.put("error", "操作错误");
			return "nlifeProduct/productConfig/edit";
		}
		NlifeProd tradProdInst = nProductService.queryProdInfoById(prodCode);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("prodCode", prodCode);
		if("Y".equals(tradProdInst.getIsRation())){
			List<NlifeRation> rationList = nlifeRationService.queryRationInfo(map);//加载保障计划信息
			model.put("rationList", rationList);
		}
		List<NlifeRisk> riskList = nlifeRiskService.queryNlifeRiskByParam(map);
		loadPageDictData(model);//加载编辑页面产品信息
		//通过产品模板代码加载产品大类 risk_main_type,1为学平险
		String riskMainType = "";
		NlifeCoreProd nlifeCoreProd = nlifeCoreProdDao.queryById(tradProdInst.getCoreProdCode());
		if(nlifeCoreProd != null) riskMainType = nlifeCoreProd.getRiskMainType();
		model.put("riskMainType",riskMainType);
		model.put("product",tradProdInst);
		List<DictDto>dics=DictCache.getDict(Constants.DICT_SPECIAL_INFO_TYPE);
		List<DictDto>epolicys=DictCache.getDict(Constants.DICT_EPOLICY_LIST);
		model.put("infoTypes", dics);
		model.put("epolicys", epolicys);
		model.put("securityplans", getSecurityPlan(tradProdInst.getCoreProdCode()));
		model.put("riskCount", riskList.size());
		return "nlifeProduct/productConfig/edit";
	}

	//跳转信保通条款算法配置
	@RequestMapping(value = "/XBTInsureEditRequest")
	public String XBTInsureEditRequest(ModelMap model,String prodCode,String riskCode,String covId,String rationId)throws Exception{
		NlifeProd prod = nProductService.queryProdInfoById(prodCode);
		model.put("covId", covId);
		model.put("tradProdCode", prodCode);
		model.put("riskCode", riskCode);
		model.put("tradProdDesc", prod.getProdName());
		model.put("currCoreProdCode", prod.getCoreProdCode());
		model.put("currCoreProdName", prod.getCoreProdName());
		List<NlifeProd> coreProdCodels = nProductService.queryAllCoreProdInfoList();//查询所有核心产品模板
		model.put("coreProdCodels", coreProdCodels);
		model.put("rationId", rationId);
		return "nlifeProduct/productConfig/insurance/XBTedit";
	}



	private List<DictDto> getSecurityPlan(String instCode){
		Integer other=0;
		List<DictDto> dictDtos1=new ArrayList<DictDto>();
		if("2039".equals(instCode)){
			other=1;
		}
		if("2039".equals(instCode)||"2030".equals(instCode)){
			List<DictDto> dictDtos=DictCache.getDict(Constants.DICT_SECURITY_PLAN);
			if (dictDtos!=null) {
				for (DictDto dictDto : dictDtos) {
					if(Integer.parseInt(dictDto.getOtherCode())<=other){
						dictDtos1.add(dictDto);
					}
				}
			}
		}
		return dictDtos1;
	}
	@RequestMapping(value = "/updateNewLifeProdInfo")
	public @ResponseBody Page<NlifeProd> updateNewLifeProdInfo(String prodCode,
															   String prodName, String coreProdCode, String appType,
															   String instant, Long maxDelayDay, Long minDelayDay, Long maxDays,
															   Long minDays, String pppUnit, Long maxNumber, String prodType,
															   String poolType, String ageLimit, Integer minAge, Integer maxAge,String minAgeUnit,String maxAgeUnit,
															   String maxOccupLevel, String insuredNoLimit, Integer minInsuredNo,
															   String agentType, String adjustStr, String status,HttpServletRequest request,Long longestCancelDay,String special,
															   String isSocial,String waitStage,String yearDeductible,BigDecimal payRate,String isSuppleCare,String epolicyCode,String epolicyTitle,String securityplan,
															   String isCityIllness, String coPayRate,String minDelayUnit,String rations,String isRation,String premiumCheck,BigDecimal pjfee,String isPjfee,String planType,String riskMainType,
															   String continueMaxAge , String continueMaxAgeUnit , String claimLimit , String graceStage ,String isByStaged,String isInform,String isInternetClause) throws Exception{
		Page<NlifeProd> page =new Page<NlifeProd>();
		if(StrUtil.isEmpty(prodCode)){
			page.setMessage("交易系统产品代码不能为空！");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(coreProdCode)){
			page.setMessage("产品模板代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(prodName)){
			page.setMessage("交易系统产品名称不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(appType)){
			page.setMessage("交易系统投保类型不能为空");
			page.setResult("error");
			return page;
		}/*else if(StrUtil.isEmpty(prodType)){
			page.setMessage("产品类型不能为空");
			page.setResult("error");
			return page;
		}*/

		if(StrUtil.isEmpty(longestCancelDay)){
			page.setMessage("最长注销天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(longestCancelDay.toString());
			if(!matcher.matches()){
				page.setMessage("最长注销天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}

		if(StrUtil.isEmpty(minDelayDay)){
			page.setMessage("最短延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*|-[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(minDelayDay.toString());
			if(!matcher.matches()){
				page.setMessage("最短延时起保天数必须是整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(maxDelayDay)){
			page.setMessage("最长延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
			Matcher matcher = pattern.matcher(maxDelayDay.toString());
			if(!matcher.matches()){
				page.setMessage("最长延时起保天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}else{
				if(maxDelayDay<minDelayDay){
					page.setMessage("最长延时起保天数不能小于最短延时起保天数");
					page.setResult("error");
					return page;
				}
			}
		}

		if(StrUtil.isEmpty(minDays)){
			page.setMessage("最小保险期间不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(minDays.toString());
			if(!matcher.matches()){
				page.setMessage("最小保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(maxDays)){
			page.setMessage("最大保险期间不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(maxDays.toString());
			if(!matcher.matches()){
				page.setMessage("最大保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}else{
				if(maxDays<minDays){
					page.setMessage("最大保险期间不能小于最小保险期间");
					page.setResult("error");
					return page;
				}
			}
		}
		if(StrUtil.isEmpty(pppUnit)){
			page.setMessage("保险期间类型不能为空");
			page.setResult("error");
			return page;
		}
		if(StrUtil.isEmpty(ageLimit)){
			page.setMessage("请选择投保年龄限制");
			page.setResult("error");
			return page;
		}

		if(StrUtil.isEmpty(instant)){
			page.setMessage("即时投保限制不能为空");
			page.setResult("error");
			return page;
		}

		if(StrUtil.isEmpty(status)){
			page.setMessage("状态不能为空，请选择");
			page.setResult("error");
			return page;
		} else {
			if ("0".equals(status)) {// 无效
				if (nProductService.isExistLinkPlanByProdCode(prodCode)) {// 存在方案
					page.setMessage("您选择的产品已配置投保方案信息，不允许改为无效");
					page.setResult("error");
					return page;
				}
			}
		}
		//编辑产品时判断产品状态
		if("1".equals(status)){
			boolean flag=false;
			/**判断产品是多主险还是单主险*/
			Map<String, String> map1=new HashMap<String, String>();
			map1.put("coreRiskCode", coreProdCode);
			if(nProductService.queryRiskType(map1)==1){
				flag=nProductService.queryPrimaryRiskIsExist(prodCode);
			}else{
				flag=nProductService.queryPrimaryRiskIsExist1(prodCode);
				if(!flag){
					if(1==nProductService.queryPrimaryRiskIsExist3(prodCode)){
						flag=nProductService.queryPrimaryRiskIsExist(prodCode);
					}
				}

			}
			if(!flag){
				page.setResult("other");
				return page;
			}else if(!"00".equalsIgnoreCase(poolType) && !nProductService.searchProdConInsureInfoByProdCode(prodCode)){
				page.setMessage("共保信息配置未完成产品只能为无效状态！请先配置共保信息后修改状态");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(insuredNoLimit)){
			page.setMessage("请选择最低投保人数限制");
			page.setResult("error");
			return page;
		}else{
			if("Y".equals(insuredNoLimit)){
				if(null==minInsuredNo){
					page.setMessage("请输入最低投保人数");
					page.setResult("error");
					return page;
				}else{
					if(minInsuredNo>99999||minInsuredNo<0){
						page.setMessage("最低投保人数为0-99999的有效整数");
						page.setResult("error");
						return page;
					}
				}
			}
		}
		if(StrUtil.isEmpty(maxNumber)){
			page.setMessage("最大份数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
			Matcher matcher = pattern.matcher(maxNumber.toString());
			if(!matcher.matches()){
				page.setMessage("最大份数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		/*if(StrUtil.isEmpty(agentType)){
			page.setMessage("请选择销售类型");
			page.setResult("error");
			return page;
		}*/
		//增加时间:2019/8/27,批减手续费选项(is_pjfee) Y是  N否,当选Y时显示一个输入框，可以输入0至1之间小数,
		//此输入框是批减扣除手续费比例(pjfee) 不输入时默认为0
		if("Y".equals(isPjfee) && pjfee != null) {
			String checkPjfee = pjfee.toString();
			Pattern pattern = Pattern.compile("^0\\.[0-9]*[1-9][0-9]*$");
			Matcher matcher = pattern.matcher(checkPjfee.toString());
			if(!"".equals(checkPjfee) && !"0".equals(checkPjfee) && !matcher.matches()){
				page.setMessage("批减扣除手续费必须是0至1之间小数");
				page.setResult("error");
				return page;
			}
		}
		//特殊产品标识 A2 广西学平险增加方案类型选项（A款 0000001，B款 0000002）
		if("1".equals(riskMainType) && "A2".equals(special) && StrUtil.isEmpty(planType)) {
			page.setMessage("广西学平险增加方案类型选项不能为空");
			page.setResult("error");
			return page;
		}

		//录入续保相关信息 , 若录入时间则必录单位, 不能只录入时间不录入单位
		//允许两个都为空
		if(continueMaxAge != null &&! "".equals(continueMaxAge) && "Y".equals(ageLimit)){
			if(continueMaxAgeUnit == null || StrUtil.isEmpty(continueMaxAgeUnit)){
				page.setMessage("请录入续保时间单位");
				page.setResult("error");
				return page;
			}else if(Double.parseDouble(continueMaxAge) < 1){
				page.setMessage("续保时间输入不合法");
				page.setResult("error");
				return page;
			}
		}



		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		// set property
		NlifeProd tradProdInst=new NlifeProd();
		tradProdInst.setProdCode(prodCode);
		tradProdInst.setProdName(prodName);
		tradProdInst.setCoreProdCode(coreProdCode);
		tradProdInst.setAppType(appType);
		tradProdInst.setProdType(prodType);
		tradProdInst.setInstant(instant);
		tradProdInst.setMaxDelayDay(maxDelayDay);
		tradProdInst.setMinDelayDay(minDelayDay);
		tradProdInst.setMaxDays(maxDays);
		tradProdInst.setMinDays(minDays);
		tradProdInst.setPppUnit(pppUnit);
		tradProdInst.setMaxNumber(maxNumber);
		tradProdInst.setStatus(status);
		tradProdInst.setPoolType(poolType);
		tradProdInst.setAgeLimit(ageLimit);
		tradProdInst.setMinAge(minAge);
		tradProdInst.setMaxAge(maxAge);
		tradProdInst.setMinAgeUnit(minAgeUnit);
		tradProdInst.setMaxAgeUnit(maxAgeUnit);
		tradProdInst.setMaxOccupLevel(maxOccupLevel);
		tradProdInst.setInsuredNoLimit(insuredNoLimit);
		tradProdInst.setMinInsuredNo(minInsuredNo);
		tradProdInst.setAdjustStr(adjustStr);
		/*tradProdInst.setAgentType(agentType);*/
		tradProdInst.setOperTime(new Date());
		tradProdInst.setLongestCancelDay(longestCancelDay);
		tradProdInst.setOprateCode(user.getUserCode());
		tradProdInst.setSpecial(special);
		tradProdInst.setIsSocial(isSocial);
		tradProdInst.setWaitStage(waitStage);
		tradProdInst.setYearDeductible(yearDeductible);
		tradProdInst.setPayRate(payRate);
		tradProdInst.setIsSuppleCare(isSuppleCare);
		tradProdInst.setEpolicyCode(epolicyCode);
		tradProdInst.setEpolicyTitle(epolicyTitle);
		tradProdInst.setSecurityplan(securityplan);
		tradProdInst.setIsCityIllness(isCityIllness);
		tradProdInst.setCoPayRate(coPayRate);
		tradProdInst.setIsRation(isRation);
		tradProdInst.setMinDelayUnit(minDelayUnit);
		tradProdInst.setRation(rations);
		tradProdInst.setIsPjfee(isPjfee);
		tradProdInst.setPjfee(pjfee);
		tradProdInst.setPlanType(planType);
		tradProdInst.setClaimLimit(claimLimit);
		tradProdInst.setGraceStage(graceStage);
		tradProdInst.setIsByStaged(isByStaged);
		tradProdInst.setIsInform(isInform);
		tradProdInst.setIsInternetClause(isInternetClause);
		if(continueMaxAge != null && continueMaxAgeUnit != null){
			tradProdInst.setContinueMaxAge(continueMaxAge);
			tradProdInst.setContinueMaxAgeUnit(continueMaxAgeUnit);
		}

		if(StrUtil.isNotEmpty(premiumCheck)){
			tradProdInst.setPremiumCheck(premiumCheck);
		}
		page.setType(nProductService.updateProd(tradProdInst));
		return page;
	}

	@RequestMapping(value = "/deleteNewLifeProdInfo")
	public @ResponseBody Page<NlifeProd> deleteNewLifeProdInfo(String tradProdCode) throws Exception{
		Page<NlifeProd> page=new Page<NlifeProd>();
		if(StrUtil.isEmpty(tradProdCode)){
			page.setMessage("产品代码参数错误，请稍后重试");
			page.setResult("error");
		}
		NlifeProd tradProdInst = nProductService.queryProdInfoById(tradProdCode);
		if(null!=tradProdInst && StrUtil.isNotEmpty(tradProdInst.getStatus())){
			if("0".equals(tradProdInst.getStatus())){
				if(nProductService.isExistLinkPlanByProdCode(tradProdCode)){
					page.setMessage("您选择的产品已配置投保方案信息，不允许删除");
					page.setResult("error");
					return page;
				}
				nProductService.deleteProdConInsureByProdCode(tradProdCode);
				nProductService.deleteCovInfoByProdCode(tradProdCode);
				nProductService.deleteRiskInfoByProdCode(tradProdCode);
				/**删除电子保单模板*/
				tradProdPropDao.deleteProdProp(tradProdCode);
				TradProdInst queryTem = new TradProdInst();
				queryTem.setTradProdCode(tradProdCode);
				tradFeeAdjustConditionDao.deleteTradFeeAdjustConditionsByTradProdCode(queryTem);
				nProductService.deleteAllRationByProdCode(tradProdCode);
				nProductService.deleteProd(tradProdCode);
				List<NlifePlan> tradInsuPlanLists = nlifePlanDao.queryPartnerInfoByProdCode(tradProdCode);
				if(null!= tradInsuPlanLists && tradInsuPlanLists.size()>0){
					gatewayChannelInfoConfigService.clearAllNewLifeCacheByChannelCodeExtend(tradInsuPlanLists);
				}
				//删除产品同时删除产品算法
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("prodCode", tradProdCode);
				tradeFeeCovService.deleteTradeCov1(map);
				page.setMessage("删除成功");
				return page;
			}else {
				page.setMessage("您选择的产品当前为有效状态,暂不能删除");
				page.setResult("error");
				return page;
			}
		}
		page.setMessage("操作错误");
		page.setResult("error");
		return page;
	}

	@RequestMapping(value = "/newLifeRiskAddReq")
	public String prodRiskAppReq(ModelMap model,HttpServletRequest request,String tradProdCode) throws Exception {
		if(StrUtil.isEmpty(tradProdCode)){
			throw new Exception("参数错误，请稍后重试");
		}
		NlifeProd prod = nProductService.queryProdInfoById(tradProdCode);
		if(null==prod){
			throw new Exception("产品代码不存在");
		}
		model.put("tradProdCode", tradProdCode);
		model.put("tradProdDesc", prod.getProdName());
		model.put("currCoreProdCode", prod.getCoreProdCode());
		model.put("currCoreProdName", prod.getCoreProdName());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("prodCode", tradProdCode);
		List<NlifeRation> rationList = nlifeRationService.queryRationInfo(map);
		List<NlifeProd> coreProdCodels = nProductService.queryAllCoreProdInfoList();//查询所有核心产品模板
		model.put("coreProdCodels", coreProdCodels);
		model.put("rationList", rationList);
		return "nlifeProduct/productConfig/insurance/add";
	}
	
	@RequestMapping(value = "/copyAddReq")
	public String copyAddReq(ModelMap modelMap, String prodCode) throws Exception {
		// 被复制的产品信息
		NlifeProd tradProdInst = nProductService.queryProdInfoById(prodCode);
		loadPageDictData(modelMap);
		List<DictDto>dics=DictCache.getDict(Constants.DICT_SPECIAL_INFO_TYPE);
		List<DictDto>epolicys=DictCache.getDict(Constants.DICT_EPOLICY_LIST);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("prodCode", prodCode);
		if("Y".equals(tradProdInst.getIsRation())){
			List<NlifeRation> rationList = nlifeRationService.queryRationInfo(map);//加载保障计划信息
			modelMap.put("rationList", rationList);
		}
		modelMap.put("riskMainType",tradProdInst.getRiskMainType());
		modelMap.put("infoTypes", dics);
		modelMap.put("epolicys", epolicys);
		modelMap.put("copiedProdCode", prodCode);
		nProductService.toCopyAddNlifeProduct(modelMap, prodCode);
		return "nlifeProduct/productConfig/edit";
	}
	
	/**
	 * 复制新增存储产品信息
	 */
	@RequestMapping(value = "saveCopyAddNlifeProduct")
	public @ResponseBody Page<NlifeProd> saveCopyAddNlifeProduct(String prodName, String copiedProdCode,
	                                                             String coreProdCode, String appType, String instant,
	                                                             Long maxDelayDay, Long minDelayDay, Long maxDays, Long minDays,
	                                                             String pppUnit, Long maxNumber, String prodType, String poolType,
	                                                             String ageLimit, Integer minAge, Integer maxAge, String minAgeUnit, String maxAgeUnit,
	                                                             String maxOccupLevel, String insuredNoLimit, Integer minInsuredNo,
	                                                             String agentType, String adjustStr, HttpServletRequest request, Long longestCancelDay,
	                                                             String special, String isSocial, String waitStage, String yearDeductible, BigDecimal payRate,
	                                                             String isSuppleCare, String epolicyCode, String epolicyTitle, String securityplan,
	                                                             String isCityIllness, String coPayRate, String minDelayUnit, String rations,
	                                                             String isRation, String premiumCheck, String isPjfee, BigDecimal pjfee, String planType,
	                                                             String riskMainType, String continueMaxAge, String continueMaxAgeUnit, String claimLimit,
	                                                             String graceStage, String isByStaged, String isInform, String isInternetClause
	) throws Exception {
		Page<NlifeProd> page =new Page<NlifeProd>();
		if(StrUtil.isEmpty(coreProdCode)){
			page.setMessage("产品模板代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(prodName)){
			page.setMessage("交易系统产品名称不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(poolType)){
			page.setMessage("共保选项不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(appType)){
			page.setMessage("交易系统投保类型不能为空");
			page.setResult("error");
			return page;
		}/*else if(StrUtil.isEmpty(prodType)){
			page.setMessage("产品类型不能为空");
			page.setResult("error");
			return page;
		}*/
		if(StrUtil.isEmpty(minDelayDay)){
			page.setMessage("最短延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*|-[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(minDelayDay.toString());
			if(!matcher.matches()){
				page.setMessage("最短延时起保天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(longestCancelDay)){
			page.setMessage("最长注销天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(longestCancelDay.toString());
			if(!matcher.matches()){
				page.setMessage("最长注销天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		
		if(StrUtil.isEmpty(maxDelayDay)){
			page.setMessage("最长延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*|-[1-9][0-9]*)$");
			Matcher matcher = pattern.matcher(maxDelayDay.toString());
			if(!matcher.matches()){
				page.setMessage("最长延时起保天数必须是整数");
				page.setResult("error");
				return page;
			}else{
				if(maxDelayDay<minDelayDay){
					page.setMessage("最长延时起保天数不能小于最短延时起保天数");
					page.setResult("error");
					return page;
				}
			}
		}
		if(StrUtil.isEmpty(minDays)){
			page.setMessage("最小保险期间不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(minDays.toString());
			if(!matcher.matches()){
				page.setMessage("最小保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(maxDays)){
			page.setMessage("最大保险期间不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(maxDays.toString());
			if(!matcher.matches()){
				page.setMessage("最大保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}else{
				if(maxDays<minDays){
					page.setMessage("最大保险期间不能小于最小保险期间");
					page.setResult("error");
					return page;
				}
			}
		}
		if(StrUtil.isEmpty(pppUnit)){
			page.setMessage("保险期间类型不能为空");
			page.setResult("error");
			return page;
		}
		if(StrUtil.isEmpty(instant)){
			page.setMessage("即时投保限制不能为空");
			page.setResult("error");
			return page;
		}
		if(StrUtil.isEmpty(ageLimit)){
			page.setMessage("请选择投保年龄限制");
			page.setResult("error");
			return page;
		}
		if(StrUtil.isEmpty(insuredNoLimit)){
			page.setMessage("请选择最低投保人数限制");
			page.setResult("error");
			return page;
		}else{
			if("Y".equals(insuredNoLimit)){
				if(null==minInsuredNo){
					page.setMessage("请输入最低投保人数");
					page.setResult("error");
					return page;
				}else{
					if(minInsuredNo>99999||minInsuredNo<0){
						page.setMessage("最低投保人数为0-99999的有效整数");
						page.setResult("error");
						return page;
					}
				}
			}
		}
		if(StrUtil.isEmpty(maxNumber)){
			page.setMessage("最大份数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
			Matcher matcher = pattern.matcher(maxNumber.toString());
			if(!matcher.matches()){
				page.setMessage("最大份数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		//增加时间:2019/8/27,批减手续费选项(is_pjfee) Y是  N否,当选Y时显示一个输入框，可以输入0至1之间小数,
		//此输入框是批减扣除手续费比例(pjfee) 不输入时默认为0
		if("Y".equals(isPjfee) && pjfee != null) {
			String checkPjfee = pjfee.toString();
			Pattern pattern = Pattern.compile("^0\\.[0-9]*[1-9][0-9]*$");
			Matcher matcher = pattern.matcher(checkPjfee.toString());
			if(!"".equals(checkPjfee) && !"0".equals(checkPjfee) && !matcher.matches()){
				page.setMessage("批减扣除手续费必须是0至1之间小数");
				page.setResult("error");
				return page;
			}
		}
		//特殊产品标识 A2 广西学平险增加方案类型选项（A款 0000001，B款 0000002）
		if("1".equals(riskMainType) && "A2".equals(special) && StrUtil.isEmpty(planType)) {
			page.setMessage("广西学平险增加方案类型选项不能为空");
			page.setResult("error");
			return page;
		}
		//录入续保相关信息 , 若录入时间则必录单位, 不能只录入时间不录入单位
		//允许两个都为空
		if(continueMaxAge != null &&! "".equals(continueMaxAge) && "Y".equals(ageLimit)){
			if(continueMaxAgeUnit == null || StrUtil.isEmpty(continueMaxAgeUnit)){
				page.setMessage("请录入续保时间单位");
				page.setResult("error");
				return page;
			}else if(Double.parseDouble(continueMaxAge) < 1){
				page.setMessage("续保时间输入不合法");
				page.setResult("error");
				return page;
			}
		}
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		NlifeProd tradProdInst=new NlifeProd();
		tradProdInst.setProdName(prodName);
		tradProdInst.setCoreProdCode(coreProdCode);
		tradProdInst.setAppType(appType);
		tradProdInst.setInstant(instant);
		tradProdInst.setMaxDelayDay(maxDelayDay);
		tradProdInst.setMinDelayDay(minDelayDay);
		tradProdInst.setMaxDays(maxDays);
		tradProdInst.setMinDays(minDays);
		tradProdInst.setPppUnit(pppUnit);
		tradProdInst.setMaxNumber(maxNumber);
		tradProdInst.setStartDate(new Date());
		tradProdInst.setStatus("0");
		tradProdInst.setProdType(prodType);
		tradProdInst.setPoolType(poolType);
		tradProdInst.setAgeLimit(ageLimit);
		tradProdInst.setMaxAge(maxAge);
		tradProdInst.setMinAge(minAge);
		tradProdInst.setMaxAgeUnit(maxAgeUnit);
		tradProdInst.setMinAgeUnit(minAgeUnit);
		tradProdInst.setMaxOccupLevel(maxOccupLevel);
		tradProdInst.setInsuredNoLimit(insuredNoLimit);
		tradProdInst.setMinInsuredNo(minInsuredNo);
		tradProdInst.setAdjustStr(adjustStr);
		tradProdInst.setOprateCode(user.getUserCode());
		tradProdInst.setLongestCancelDay(longestCancelDay);
		tradProdInst.setSpecial(special);
		tradProdInst.setIsSocial(isSocial);
		tradProdInst.setWaitStage(waitStage);
		tradProdInst.setYearDeductible(yearDeductible);
		tradProdInst.setPayRate(payRate);
		tradProdInst.setIsSuppleCare(isSuppleCare);
		tradProdInst.setEpolicyCode(epolicyCode);
		tradProdInst.setEpolicyTitle(epolicyTitle);
		tradProdInst.setSecurityplan(securityplan);
		tradProdInst.setIsCityIllness(isCityIllness);
		tradProdInst.setCoPayRate(coPayRate);
		tradProdInst.setRation(rations);
		tradProdInst.setMinDelayUnit(minDelayUnit);
		tradProdInst.setIsRation(isRation);
		tradProdInst.setIsPjfee(isPjfee);
		tradProdInst.setPjfee(pjfee);
		tradProdInst.setPlanType(planType);
		tradProdInst.setClaimLimit(claimLimit);
		tradProdInst.setGraceStage(graceStage);
		tradProdInst.setRiskMainType(riskMainType);
		tradProdInst.setIsByStaged(isByStaged);
		tradProdInst.setIsInform(isInform);
		tradProdInst.setIsInternetClause(isInternetClause);
		if(continueMaxAge != null && continueMaxAgeUnit != null){
			tradProdInst.setContinueMaxAge(continueMaxAge);
			tradProdInst.setContinueMaxAgeUnit(continueMaxAgeUnit);
		}
		if(StrUtil.isNotEmpty(premiumCheck)){
			tradProdInst.setPremiumCheck(premiumCheck);
		}
		String[] product = {copiedProdCode};
		// 使用产品导出功能获取产品信息的插入语句
		Map<String, Object> map = queryNlife(product);
		// 去掉产品SQL，使用saveProd方法保存
		map.remove("list");
		map.remove("props");
		String sql = FreeMarkerUtil.process("nlifeProd.ftl", map);
		//目的得到添加产品编号便与险种配置
		NlifeProd nlifeProd = nProductService.copyAddProd(tradProdInst);
		page.setType(nlifeProd);
		String prodCode = nlifeProd.getProdCode();
		String replaceCopiedProdCode = replaceProdCode(copiedProdCode);
		String impSql = sql.replaceAll(replaceCopiedProdCode, prodCode);
		logger.info(impSql);
		try {
			nProductService.importAllProdInfo(impSql);
		} catch (Exception e) {
			tradProdPropDao.deleteProdProp(prodCode);
			nProductService.deleteProd(prodCode);
			logger.info(e.getMessage());
			page.setMessage("系统错误，请联系管理员" + e.getMessage());
			page.setResult("error");
		}
		return page;
	}
	
	@RequestMapping(value = "/loadCoreProdRisk")
	public @ResponseBody Page<NlifeCoreProdRisk> loadCoreProdRisk(ModelMap model,Integer size,Integer current,String tradProdCode,
	                                                              String coreProdCode, String riskCode, String riskName) throws Exception{
		Page<NlifeCoreProdRisk> page=new Page<NlifeCoreProdRisk>();
		if(StrUtil.isEmpty(coreProdCode) || StrUtil.isEmpty(tradProdCode)){
			page.setResult("error");
			page.setMessage("产品代码参数不能为空！");
			return page;
		}
		//验证产品代码是否可用TradProdInst
		NlifeProd tradProdInst= nProductService.queryProdInfoById(tradProdCode);
		if(null == tradProdInst){
			page.setResult("error");
			page.setMessage("产品代码错误，请核实后重试！");
			return page;
		}
		//险种模板表
		page.setCurrent(current);
		page.setSize(size);
		return nProductService.queryCoreProdRiskTempletPageById(page,coreProdCode,tradProdCode, riskCode, riskName);
	}

	@RequestMapping(value = "/loadAddedRiskInfo")
	public @ResponseBody List<NlifeRation> loadAddedRiskInfo(String tradProdCode) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("prodCode", tradProdCode);
		return nProductService.queryRiskAndRationByParam(map);
	}

	@RequestMapping(value="/saveRiskInfoBatch")
	public @ResponseBody Page<NlifeRisk> saveRiskInfoBatch (@RequestBody List<Map<String, String>> params, HttpServletRequest request) throws Exception {
		List<Page<NlifeRisk>> pageList = new ArrayList<Page<NlifeRisk>>();
		for (Map<String, String> param : params) {
			NlifeRisk nr = new NlifeRisk();
			nr.setCoreRiskCode(param.get("coreRiskCode"));
			nr.setPrmryFlag(param.get("corePrmryFlag"));
			nr.setRiskType(param.get("riskType"));
			nr.setRiskName(param.get("riskName"));
			nr.setRationId(param.get("rationId"));
			nr.setRationName(param.get("rationName"));
			nr.setProdCode(param.get("prodCode"));
			String currCoreProdCode = param.get("currCoreProdCode");
			String chooseCoreProdCode = param.get("coreProdCode");
			Page<NlifeRisk> page=new Page<NlifeRisk>();
			NlifeProd np = nlifeProdDao.queryProdInfoById(nr.getProdCode());
			int mainRiskCount=nlifeRiskDao.queryMainRiskCount(nr.getProdCode());
			if(null == nr || StrUtil.isEmpty(currCoreProdCode) || StrUtil.isEmpty(chooseCoreProdCode)){
				page.setMessage("参数错误，请稍后重试");
				page.setResult("error");
				return page;
			}else if(StrUtil.isEmpty(nr.getProdCode())){
				page.setMessage("产品代码不能为空");
				page.setResult("error");
				return page;
			}else if(StrUtil.isEmpty(nr.getCoreRiskCode())){
				page.setMessage("条款代码不能为空");
				page.setResult("error");
				return page;
			}else if(StrUtil.isEmpty(nr.getRiskName())){
				page.setMessage("交易系统条款名称不能为空");
				page.setResult("error");
				return page;
			}else if(StrUtil.isEmpty(nr.getPrmryFlag())){
				page.setMessage("主附条款标识不能为空");
				page.setResult("error");
				return page;
			}else if(nProductService.queryNlifeRiskIsExits(nr)){
				page.setMessage(nr.getCoreRiskCode() + "此保障计划已存在该条款");
				page.setResult("error");
				return page;
			}
			boolean flag=false;
			if("0".equals(nr.getPrmryFlag())){
				NlifeRisk temObj = new NlifeRisk();
				temObj.setProdCode(nr.getProdCode());
				temObj.setRationId(nr.getRationId());
				Map<String, String> map = new HashMap<String, String>();
				map.put("coreRiskCode", chooseCoreProdCode);
				/**判断是否是多主险**/
				List<NlifeRisk> rlist = nlifeRiskDao.queryMainRisk(nr.getProdCode());
				if(nProductService.queryRiskType(map) > 1 && mainRiskCount >= 1 && rlist.size() > 0){
					String singleOrGroup = np.getAppType();//0 个单，1 团单
					String unit = np.getPppUnit();//保险期限单位，y 年，m 月，d 天，h 时
					Long maxTime = np.getMaxDays();
					NlifeRisk nr1 = rlist.get(0);
					NlifeCoreRisk nlifeCoreRisk1 = nlifeCoreRiskDao.queryCoreRiskById( nr1.getCoreRiskCode());
					NlifeCoreRisk nlifeCoreRisk2 = nlifeCoreRiskDao.queryCoreRiskById(nr.getCoreRiskCode());
					if( rlist.size() == 1 && mainRiskCount == 1 && null!=nlifeCoreRisk1.getOneYearSingle() && null!=nlifeCoreRisk2.getOneYearSingle()){
						//个单
						if("0".equalsIgnoreCase(singleOrGroup)) {
							if ("y".equalsIgnoreCase(unit)) {
								if (maxTime > 1){
									//条款比例上限 MoreYearSingle
									if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearSingle
									if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								}
							}
							if ("m".equalsIgnoreCase(unit)) {
								if (maxTime > 12){
									//条款比例上限 MoreYearSingle
									if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearSingle
									if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}

								}
							}
							if ("d".equalsIgnoreCase(unit)) {
								if (maxTime > 365){
									//条款比例上限 MoreYearSingle
									if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearSingle
									if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}

								}
							}
							if ("h".equalsIgnoreCase(unit)) {
								if (maxTime > 8760){
									//条款比例上限 MoreYearSingle
									if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearSingle
									if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}

								}
							}
						}    //团单
						if("1".equalsIgnoreCase(singleOrGroup)) {
							if ("y".equalsIgnoreCase(unit)) {
								if (maxTime > 1){
									//条款比例上限 MoreYearGroup
									if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearGroup
									if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								}
							}
							if ("m".equalsIgnoreCase(unit)) {
								if (maxTime > 12){
									//条款比例上限 MoreYearGroup
									if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearGroup
									if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}

								}
							}
							if ("d".equalsIgnoreCase(unit)) {
								if (maxTime > 365){
									//条款比例上限 MoreYearGroup
									if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearGroup
									if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}

								}
							}
							if ("h".equalsIgnoreCase(unit)) {
								if (maxTime > 8760){
									//条款比例上限 MoreYearGroup
									if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}
								} else{//条款比例上限 OneYearGroup
									if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
										nr.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr);
									} else{
										nr1.setPrmryFlag("2");
										nlifeRiskDao.updateRisk(nr1);
									}

								}
							}
						}
					}
					if( rlist.size() == 1 && mainRiskCount == 1 && (null == nlifeCoreRisk1.getOneYearSingle() || null == nlifeCoreRisk2.getOneYearSingle())){
						if(null == nlifeCoreRisk1.getOneYearSingle()){
							nr.setPrmryFlag("2");
							nlifeRiskDao.updateRisk(nr);
						}
						if(null != nlifeCoreRisk1.getOneYearSingle() && null == nlifeCoreRisk2.getOneYearSingle()){
							nr1.setPrmryFlag("2");
							nlifeRiskDao.updateRisk(nr1);
						}
					}
					if(mainRiskCount >= 2) {
						NlifeRisk firstRisk = nlifeRiskDao.queryFirstRisk(nr.getProdCode());
						NlifeCoreRisk coreRisk = nlifeCoreRiskDao.queryCoreRiskById(firstRisk.getCoreRiskCode());
						NlifeCoreRisk coreRisk2 = nlifeCoreRiskDao.queryCoreRiskById(nr.getCoreRiskCode());
						if (null != coreRisk.getOneYearSingle() && null != coreRisk2.getOneYearSingle()) {
							//个单
							if ("0".equalsIgnoreCase(singleOrGroup)) {
								if ("y".equalsIgnoreCase(unit)) {
									if (maxTime > 1) {
										//条款比例上限 MoreYearSingle
										if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearSingle
										if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									}
								}
								if ("m".equalsIgnoreCase(unit)) {
									if (maxTime > 12) {
										//条款比例上限 MoreYearSingle
										if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearSingle
										if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									}
								}
								if ("d".equalsIgnoreCase(unit)) {
									if (maxTime > 365) {
										//条款比例上限 MoreYearSingle
										if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearSingle
										if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									}
								}
								if ("h".equalsIgnoreCase(unit)) {
									if (maxTime > 8760) {
										//条款比例上限 MoreYearSingle
										if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearSingle
										if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									}
								}
							}    //团单
							if ("1".equalsIgnoreCase(singleOrGroup)) {
								if ("y".equalsIgnoreCase(unit)) {
									if (maxTime > 1) {
										//条款比例上限 MoreYearGroup
										if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearGroup
										if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									}
								}
								if ("m".equalsIgnoreCase(unit)) {
									if (maxTime > 12) {
										//条款比例上限 MoreYearGroup
										if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearGroup
										if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}

									}
								}
								if ("d".equalsIgnoreCase(unit)) {
									if (maxTime > 365) {
										//条款比例上限 MoreYearGroup
										if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearGroup
										if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									}
								}
								if ("h".equalsIgnoreCase(unit)) {
									if (maxTime > 8760) {
										//条款比例上限 MoreYearGroup
										if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									} else {//条款比例上限 OneYearGroup
										if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
											firstRisk.setPrmryFlag("0");
											nr.setPrmryFlag("2");
											nlifeRiskDao.updateRisk(nr);
											nlifeRiskDao.updateRisk(firstRisk);
										}
									}
								}
							}
						}
						if (null == coreRisk.getOneYearSingle() && null != coreRisk2.getOneYearSingle()){
							firstRisk.setPrmryFlag("0");
							nr.setPrmryFlag("2");
							nlifeRiskDao.updateRisk(nr);
							nlifeRiskDao.updateRisk(firstRisk);
						}
					}

					flag=true;
				}
			}
			//设置操作人，操作时间
			HttpSession session = request.getSession();
			GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
			nr.setOprateCode(user.getUserCode());
			nr.setOpratetime(new Date());
			if(nProductService.saveRisk(nr)){
				//判断产品是否互联网：
				if(mainRiskCount == 0 && "0".equalsIgnoreCase(nr.getPrmryFlag())){
					NlifeCoreRisk nlifeCoreRisk = nlifeCoreRiskDao.queryCoreRiskById( nr.getCoreRiskCode());
					if("Y".equalsIgnoreCase(nlifeCoreRisk.getIsInternetRisk())){
						np.setIsInternetClause("Y");
					} else{
						np.setIsInternetClause("N");
					}
					nProductService.updateProd(np);
				}
				if(mainRiskCount > 0){
					NlifeCoreRisk ncr = iNlifePlanConfigService.queryMainRiskOrFirstRisk(nr.getProdCode());
					if("Y".equalsIgnoreCase(ncr.getIsInternetRisk())){
						np.setIsInternetClause("Y");
					} else {
						np.setIsInternetClause("N");
					}
					nProductService.updateProd(np);
				}
				if(flag){
					/**产品大类*/
					Map<String, String> map=new HashMap<String, String>();
					map.put("tradRiskCode", nr.getCoreRiskCode());
					map.put("prodCode",nr.getProdCode());
					if(nProductService.updateRiskMain(map)){
						page.setMessage(nr.getCoreRiskCode() + "保存成功");
					}else{
						page.setResult("error");
						page.setMessage(nr.getCoreRiskCode() + "保存失败，请稍后重试");
					}
				}else {
					page.setMessage(nr.getCoreRiskCode() + "保存成功");
				}
			}else{
				page.setResult("error");
				page.setMessage(nr.getCoreRiskCode() + "保存失败，请稍后重试");
			}
			pageList.add(page);
		}
		Page<NlifeRisk> resultPage = new Page<NlifeRisk>();
		String msg = "";
		boolean resultFlag = true;
		for (Page<NlifeRisk> nlifeRiskPage : pageList) {
			msg += nlifeRiskPage.getMessage();
			if (nlifeRiskPage.getResult().equals("error")){
				resultFlag = false;
			}
		}
		resultPage.setMessage(msg);
		if (!resultFlag){
			resultPage.setResult("error");
		}
		return resultPage;
	}

	@RequestMapping(value = "/saveRiskInfo")
	public @ResponseBody Page<NlifeRisk> saveRiskInfo(NlifeRisk nr,String currCoreProdCode,String chooseCoreProdCode,HttpServletRequest request) throws Exception{
		Page<NlifeRisk> page=new Page<NlifeRisk>();
		NlifeProd np = nlifeProdDao.queryProdInfoById(nr.getProdCode());
		int mainRiskCount=nlifeRiskDao.queryMainRiskCount(nr.getProdCode());
		if(null == nr || StrUtil.isEmpty(currCoreProdCode) || StrUtil.isEmpty(chooseCoreProdCode)){
			page.setMessage("参数错误，请稍后重试");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getProdCode())){
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getCoreRiskCode())){
			page.setMessage("条款代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getRiskName())){
			page.setMessage("交易系统条款名称不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getPrmryFlag())){
			page.setMessage("主附条款标识不能为空");
			page.setResult("error");
			return page;
		}else if(nProductService.queryNlifeRiskIsExits(nr)){
			page.setMessage("此保障计划已存在该条款");
			page.setResult("error");
			return page;
		}
	/*	if(!currCoreProdCode.equals(chooseCoreProdCode)){
			nr.setPrmryFlag("1");
		}*/
		boolean flag=false;
		if("0".equals(nr.getPrmryFlag())){
			NlifeRisk temObj = new NlifeRisk();
			temObj.setProdCode(nr.getProdCode());
			temObj.setRationId(nr.getRationId());
			Map<String, String> map = new HashMap<String, String>();
			map.put("coreRiskCode", chooseCoreProdCode);
			/**判断是否是多主险**/
			List<NlifeRisk> rlist = nlifeRiskDao.queryMainRisk(nr.getProdCode());
			if(nProductService.queryRiskType(map) > 1 && mainRiskCount >= 1 && rlist.size() > 0){
				String singleOrGroup = np.getAppType();//0 个单，1 团单
				String unit = np.getPppUnit();//保险期限单位，y 年，m 月，d 天，h 时
				Long maxTime = np.getMaxDays();
				NlifeRisk nr1 = rlist.get(0);
				NlifeCoreRisk nlifeCoreRisk1 = nlifeCoreRiskDao.queryCoreRiskById( nr1.getCoreRiskCode());
				NlifeCoreRisk nlifeCoreRisk2 = nlifeCoreRiskDao.queryCoreRiskById(nr.getCoreRiskCode());
				if( rlist.size() == 1 && mainRiskCount == 1 && null!=nlifeCoreRisk1.getOneYearSingle() && null!=nlifeCoreRisk2.getOneYearSingle()){
					//个单
					if("0".equalsIgnoreCase(singleOrGroup)) {
						if ("y".equalsIgnoreCase(unit)) {
							if (maxTime > 1){
								//条款比例上限 MoreYearSingle
								if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearSingle
								if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							}
						}
						if ("m".equalsIgnoreCase(unit)) {
							if (maxTime > 12){
								//条款比例上限 MoreYearSingle
								if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearSingle
								if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}

							}
						}
						if ("d".equalsIgnoreCase(unit)) {
							if (maxTime > 365){
								//条款比例上限 MoreYearSingle
								if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearSingle
								if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}

							}
						}
						if ("h".equalsIgnoreCase(unit)) {
							if (maxTime > 8760){
								//条款比例上限 MoreYearSingle
								if (nlifeCoreRisk1.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearSingle
								if (nlifeCoreRisk1.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}

							}
						}
					}    //团单
					if("1".equalsIgnoreCase(singleOrGroup)) {
						if ("y".equalsIgnoreCase(unit)) {
							if (maxTime > 1){
								//条款比例上限 MoreYearGroup
								if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearGroup
								if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							}
						}
						if ("m".equalsIgnoreCase(unit)) {
							if (maxTime > 12){
								//条款比例上限 MoreYearGroup
								if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearGroup
								if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}

							}
						}
						if ("d".equalsIgnoreCase(unit)) {
							if (maxTime > 365){
								//条款比例上限 MoreYearGroup
								if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearGroup
								if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}

							}
						}
						if ("h".equalsIgnoreCase(unit)) {
							if (maxTime > 8760){
								//条款比例上限 MoreYearGroup
								if (nlifeCoreRisk1.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}
							} else{//条款比例上限 OneYearGroup
								if (nlifeCoreRisk1.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup())==1){
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
								} else{
									nr1.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr1);
								}

							}
						}
					}
				}
				if( rlist.size() == 1 && mainRiskCount == 1 && (null == nlifeCoreRisk1.getOneYearSingle() || null == nlifeCoreRisk2.getOneYearSingle())){
					if(null == nlifeCoreRisk1.getOneYearSingle()){
						nr.setPrmryFlag("2");
						nlifeRiskDao.updateRisk(nr);
					}
					if(null != nlifeCoreRisk1.getOneYearSingle() && null == nlifeCoreRisk2.getOneYearSingle()){
						nr1.setPrmryFlag("2");
						nlifeRiskDao.updateRisk(nr1);
					}
				}
				if(mainRiskCount >= 2) {
					NlifeRisk firstRisk = nlifeRiskDao.queryFirstRisk(nr.getProdCode());
					NlifeCoreRisk coreRisk = nlifeCoreRiskDao.queryCoreRiskById(firstRisk.getCoreRiskCode());
					NlifeCoreRisk coreRisk2 = nlifeCoreRiskDao.queryCoreRiskById(nr.getCoreRiskCode());
					if (null != coreRisk.getOneYearSingle() && null != coreRisk2.getOneYearSingle()) {
					//个单
					if ("0".equalsIgnoreCase(singleOrGroup)) {
						if ("y".equalsIgnoreCase(unit)) {
							if (maxTime > 1) {
								//条款比例上限 MoreYearSingle
								if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearSingle
								if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							}
						}
						if ("m".equalsIgnoreCase(unit)) {
							if (maxTime > 12) {
								//条款比例上限 MoreYearSingle
								if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearSingle
								if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							}
						}
						if ("d".equalsIgnoreCase(unit)) {
							if (maxTime > 365) {
								//条款比例上限 MoreYearSingle
								if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearSingle
								if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							}
						}
						if ("h".equalsIgnoreCase(unit)) {
							if (maxTime > 8760) {
								//条款比例上限 MoreYearSingle
								if (coreRisk.getMoreYearSingle().compareTo(nlifeCoreRisk2.getMoreYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearSingle
								if (coreRisk.getOneYearSingle().compareTo(nlifeCoreRisk2.getOneYearSingle()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							}
						}
					}    //团单
					if ("1".equalsIgnoreCase(singleOrGroup)) {
						if ("y".equalsIgnoreCase(unit)) {
							if (maxTime > 1) {
								//条款比例上限 MoreYearGroup
								if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearGroup
								if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							}
						}
						if ("m".equalsIgnoreCase(unit)) {
							if (maxTime > 12) {
								//条款比例上限 MoreYearGroup
								if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearGroup
								if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}

							}
						}
						if ("d".equalsIgnoreCase(unit)) {
							if (maxTime > 365) {
								//条款比例上限 MoreYearGroup
								if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearGroup
								if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							}
						}
						if ("h".equalsIgnoreCase(unit)) {
							if (maxTime > 8760) {
								//条款比例上限 MoreYearGroup
								if (coreRisk.getMoreYearGroup().compareTo(nlifeCoreRisk2.getMoreYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							} else {//条款比例上限 OneYearGroup
								if (coreRisk.getOneYearGroup().compareTo(nlifeCoreRisk2.getOneYearGroup()) == 1) {
									firstRisk.setPrmryFlag("0");
									nr.setPrmryFlag("2");
									nlifeRiskDao.updateRisk(nr);
									nlifeRiskDao.updateRisk(firstRisk);
								}
							}
						}
					}
				}
					if (null == coreRisk.getOneYearSingle() && null != coreRisk2.getOneYearSingle()){
						firstRisk.setPrmryFlag("0");
						nr.setPrmryFlag("2");
						nlifeRiskDao.updateRisk(nr);
						nlifeRiskDao.updateRisk(firstRisk);
					}
				}

				flag=true;
			}



//			if(nProductService.queryRiskType(map)>1){
//
//				temObj.setPrmryFlag("2");
//			}else{
//				temObj.setPrmryFlag("0");
//			}
//			if(!nProductService.queryIsExistRiskPrimaryKeyByParams(temObj)){
//			/*	page.setMessage("同一产品最多只能配置一条主险条款，本产品主险条款配置已经存在");
//				page.setResult("error");
//				return page;*/
//		    	/**多主险如果不存在第一主险则为第一主险*/
//
//		    	nr.setPrmryFlag(temObj.getPrmryFlag());
//		    	flag=true;
//		    }
		}


		//设置操作人，操作时间
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		nr.setOprateCode(user.getUserCode());
		nr.setOpratetime(new Date());
		if(nProductService.saveRisk(nr)){
			//判断产品是否互联网：
			if(mainRiskCount == 0 && "0".equalsIgnoreCase(nr.getPrmryFlag())){
				NlifeCoreRisk nlifeCoreRisk = nlifeCoreRiskDao.queryCoreRiskById( nr.getCoreRiskCode());
				if("Y".equalsIgnoreCase(nlifeCoreRisk.getIsInternetRisk())){
					np.setIsInternetClause("Y");
				} else{
					np.setIsInternetClause("N");
				}
				nProductService.updateProd(np);
			}
			if(mainRiskCount > 0){
				NlifeCoreRisk ncr = iNlifePlanConfigService.queryMainRiskOrFirstRisk(nr.getProdCode());
				if("Y".equalsIgnoreCase(ncr.getIsInternetRisk())){
					np.setIsInternetClause("Y");
				} else {
					np.setIsInternetClause("N");
				}
				nProductService.updateProd(np);
			}
			if(flag){
				/**产品大类*/
				Map<String, String> map=new HashMap<String, String>();
				map.put("tradRiskCode", nr.getCoreRiskCode());
				map.put("prodCode",nr.getProdCode());
				if(nProductService.updateRiskMain(map)){
					page.setMessage("保存成功");
				}else{
					page.setResult("error");
					page.setMessage("保存失败，请稍后重试");
				}
			}else {
				page.setMessage("保存成功");
			}
			/**多主险收付代码*/
/*			if("2".equals(nr.getPrmryFlag())){
				Map<String, String> map=new HashMap<String, String>();
				map.put("coreProdCode", currCoreProdCode);
				map.put("prodCode",nr.getProdCode());
				map.put("tradRiskCode", nr.getCoreRiskCode());
				if(nProductService.updateSaleCode(map)){
					page.setMessage("保存成功");
				}else{
					page.setResult("error");
					page.setMessage("保存失败，请稍后重试");
				}
			}else{
				page.setMessage("保存成功");
			}*/
		}else{
			page.setResult("error");
			page.setMessage("保存失败，请稍后重试");
		}
		return page;
	}

	@RequestMapping(value = "/updateMRisk")
	public @ResponseBody Page<NlifeRisk> updateMRisk(String prodCode,String tradRiskCode,String coreProdCode,String rationId) throws Exception{
		Page<NlifeRisk> page=new Page<NlifeRisk>();
		if(null == prodCode||"".equals(prodCode)||tradRiskCode==null||"".equals(tradRiskCode)||null==rationId||"".equals(rationId)){
			page.setMessage("参数错误，请稍后重试");
			page.setResult("error");
			return page;
		}
		Map<String, String> map1=new HashMap<String, String>();
		map1.put("coreRiskCode", coreProdCode);
		if(nProductService.queryRiskType(map1)==1){
			page.setMessage("单主险产品不允许修改为第一主险");
			page.setResult("error");
			return page;
		}
		//有效产品处理
		NlifeProd temNlifeProd =  nProductService.queryProdInfoById(prodCode);
		if(temNlifeProd!=null&&"1".equals(temNlifeProd.getStatus())){
			//查询当前险种是否配责任
			Map<String, String> map=new HashMap<String, String>();
			map.put("prodCode",prodCode);
			map.put("coreRiskCode", tradRiskCode);
			if(!nProductService.queryPrimaryRiskIsExist2(map)){
				page.setMessage("关联产品为有效，必须配置责任");
				page.setResult("error");
				return page;
			};
		}
		if(nProductService.updateMRisk(prodCode, tradRiskCode, 0,rationId)){
			Map<String, String> map=new HashMap<String, String>();
			map.put("coreProdCode", coreProdCode);
			map.put("prodCode",prodCode);
			map.put("tradRiskCode", tradRiskCode);
			/**多主险收付代码*/
			/*if(nProductService.updateSaleCode(map)){
				page.setMessage("修改成功");
			}else{
				page.setMessage("修改失败");
				page.setResult("error");
			}*/
			/**产品大类*/
			Map<String, String> map2=new HashMap<String, String>();
			map2.put("tradRiskCode",tradRiskCode);
			map2.put("prodCode",prodCode);
			if(nProductService.updateRiskMain(map2)){
				page.setMessage("修改成功");
			}else{
				page.setResult("error");
				page.setMessage("修改失败，请稍后重试");
				return page;
			}
			//清除缓存
			//gatewayClearCacheManager.clearNlifeCacheInfoManager();
		}else{
			page.setMessage("修改失败");
			page.setResult("error");
		};
		return page;
	}


	@RequestMapping(value = "/updateRiskInfo")
	public @ResponseBody Page<NlifeRisk> updateRiskInfo(NlifeRisk nr,HttpServletRequest request) throws Exception{
		Page<NlifeRisk> page=new Page<NlifeRisk>();
		if(null == nr){
			page.setMessage("参数错误，请稍后重试");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getProdCode())){
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getCoreRiskCode())){
			page.setMessage("条款代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getRiskName())){
			page.setMessage("交易系统条款名称不能为空");
			page.setResult("error");
			return page;
		}
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		nr.setOprateCode(user.getUserCode());
		nr.setOpratetime(new Date());
		if(nProductService.updateRisk(nr)){
			page.setMessage("修改成功");
		}else{
			page.setResult("error");
			page.setMessage("修改失败，请稍后重试");
		}
		return page;
	}

	@RequestMapping(value = "/deleteRiskInfo")
	public @ResponseBody Page<NlifeRisk> deleteRiskInfo(NlifeRisk nr) throws Exception{
		Page<NlifeRisk> page=new Page<NlifeRisk>();
		if(null == nr){
			page.setMessage("参数错误，请稍后重试");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getProdCode())){
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getCoreRiskCode())){
			page.setMessage("条款代码不能为空");
			page.setResult("error");
			return page;
		}else if(StrUtil.isEmpty(nr.getPrmryFlag())){
			page.setMessage("主/附加险标识代码不能为空");
			page.setResult("error");
			return page;
		}
		/**判断险种为单主险还是多主险*/
		NlifeProd temNlifeProd =  nProductService.queryProdInfoById(nr.getProdCode());
		String flag="";
		Map<String, String> map1=new HashMap<String, String>();
		map1.put("coreRiskCode", temNlifeProd.getCoreProdCode());
		if(nProductService.queryRiskType(map1)==1){
			flag="0";
		}else{
			flag="2";
		}
		if(flag.equalsIgnoreCase(nr.getPrmryFlag())){
			if(temNlifeProd!=null &&  "1".equalsIgnoreCase(temNlifeProd.getStatus())){
				page.setMessage("本条款关联的产品状态为:[有效]，请先修改关联产品状态为:[无效]后删除");
				page.setResult("error");
				return page;
			}
		}
		NlifeCov cov = new NlifeCov();
		cov.setProdCode(nr.getProdCode());
		cov.setCoreRiskCode(nr.getCoreRiskCode());
		cov.setRationId(nr.getRationId());
		nProductService.deleteCov(cov);
		int  count = nlifeRiskDao.queryMainRiskCount(nr.getProdCode());
		if(nProductService.deleteRisk(nr)){
			NlifeRisk nlifeRisk = nlifeRiskDao.queryFirstRisk(nr.getProdCode());
			if(count == 2 && null != nlifeRisk){
				nlifeRisk.setPrmryFlag("0");
				nlifeRiskDao.updateRisk(nlifeRisk);
			}
			page.setMessage("删除成功");
		}else{
			page.setResult("error");
			page.setMessage("删除失败，请稍后重试");
		}
		return page;
	}

	@RequestMapping(value = "/queryNewLifeCoverage")
	public @ResponseBody Page<NlifeCov> queryNewLifeCoverage(NlifeCov nc) throws Exception{
		Page<NlifeCov> page = new Page<NlifeCov>();
		if(null == nc || StrUtil.isEmpty(nc.getProdCode())|| StrUtil.isEmpty(nc.getCoreRiskCode()) || StrUtil.isEmpty(nc.getRationId())){
			page.setMessage("参数错误，请稍后重试");
			page.setResult("error");
			return page;
		}
		page.setType(nc);
		return nProductService.queryCovPageByCriteria(page);
	}
	@RequestMapping(value = "/queryNewLifeCoverage1")
	public @ResponseBody Page<NlifeCov> queryNewLifeCoverage1(NlifeCov nc) throws Exception{
		Page<NlifeCov> page = new Page<NlifeCov>();
		if(null == nc || StrUtil.isEmpty(nc.getProdCode())|| StrUtil.isEmpty(nc.getCoreRiskCode()) || StrUtil.isEmpty(nc.getRationId())){
			page.setMessage("参数错误，请稍后重试");
			page.setResult("error");
			return page;
		}
		page.setType(nc);
		return nProductService.queryCovPageByCriteria1(page);
	}
	@RequestMapping(value = "/saveNewLifeCoverage")
	public @ResponseBody Page<NlifeCov> saveNewLifeCoverage(String jsonStr,HttpServletRequest request) throws Exception{
		Page<NlifeCov> page = new Page<NlifeCov>();
		if("[]".equals(jsonStr) || StrUtil.isEmpty(jsonStr)){
			page.setMessage("责任未配置，请勾选任意一条责任后保存！");
			page.setResult("error");
			return page;
		}
		List<NlifeCov> ls = new ArrayList<NlifeCov>();
		List temls = JsonUtils.parseJson(jsonStr, List.class);
		BigDecimal covAmtTem =null;
		BigDecimal noCalimAmountTem =null;
		BigDecimal claimRateTem =null;
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		for(int i=0;i<temls.size();i++){
			if(StrUtil.isNotEmpty(temls.get(i).toString())){
				NlifeCov nCov = new NlifeCov();
				logger.debug(temls.get(i).toString());
				String objJsonStr = temls.get(i).toString().replaceAll("=,","=null,");
				objJsonStr = objJsonStr.replaceAll("calId=}", "calId=null}");
				if(-1!=objJsonStr.indexOf("/")){
					String temCovName = objJsonStr.substring(objJsonStr.indexOf("covName=")+8,objJsonStr.indexOf(",",objJsonStr.indexOf("covName=")));
					objJsonStr = objJsonStr.replace(temCovName, "'"+temCovName+"'");
				}
  				nCov = JsonUtils.parseJson(objJsonStr,NlifeCov.class);
				if(null!=nCov.getCovAmt()){
					covAmtTem = nCov.getCovAmt();
					nCov.setCovAmt(new BigDecimal(decimalFormat.format(covAmtTem)));
				}
				if(null!=nCov.getNoCalimAmount()){
					noCalimAmountTem = nCov.getNoCalimAmount();
					nCov.setNoCalimAmount(new BigDecimal(decimalFormat.format(noCalimAmountTem)));
				}
				if(null!=nCov.getClaimRate()){
					claimRateTem = nCov.getClaimRate();
					nCov.setClaimRate(claimRateTem.divide(new BigDecimal(100)).setScale(5,BigDecimal.ROUND_HALF_UP));
				}
				if(StrUtil.isEmpty(nCov.getCalId())){
					nCov.setAmtType("");
				}
				//TODO
				nCov.setOprateCode(user.getUserCode());
				nCov.setOprateTime(new Date());
				ls.add(nCov);
			}
		}
		if(null!=ls && ls.size()>0){
			nProductService.deleteCov(ls.get(0));
		}
		for(NlifeCov tem :ls){
			nProductService.saveCov(tem);
		}
		page.setMessage("修改成功！");
		return page;
	}
	//共保配置
	@RequestMapping(value = "/conInsure")
	public String conInsureInfo(ModelMap model, HttpServletRequest request,String prodCode) throws Exception {
		NlifeProd prod = null;
		try {
			prod = nProductService.queryProdInfoById(prodCode);
			if (null == prod) {
				throw new AppException("产品代码不存在");
			} else if (null != prod && "00".equals(prod.getPoolType())) {
				throw new AppException("本产品不支持共保");
			}
			List<DictDto> insureCompanyTypeList = DictCache.getDict(Constants.DICT_INSURE_COMPANY_TYPE);
			model.put("insureCompanyTypeList", insureCompanyTypeList);
			model.put("prodCode", prod.getProdCode());
			model.put("prodName", prod.getProdName());
			String conInsuCodeDscp = "";
			if(StrUtil.isNotEmpty(prod.getPoolType()) && "10".equals(prod.getPoolType())){
				conInsuCodeDscp ="主共保";
			}else if(StrUtil.isNotEmpty(prod.getPoolType()) && "20".equals(prod.getPoolType())){
				conInsuCodeDscp ="从共保";
			}
			model.put("conInsuCode",conInsuCodeDscp);
		} catch (AppException e) {
			model.addAttribute("dataException", e.getMessage());
			logger.info(e);
		}
		return "nlifeProduct/productConfig/conInsure/add";
	}

	@RequestMapping(value = "/loadProdConInsureInfo")
	public @ResponseBody Page<NlifeCon> loadProdConInsureInfo(String prodCode) throws Exception{
		Page<NlifeCon> page=new Page<NlifeCon>();
		page = nProductService.queryConPageByCriteria(page, prodCode);
		return page;
	}

	@RequestMapping(value = "/saveProdConInsure")
	public @ResponseBody  Page<NlifeCon> saveProdConInsure(String jsonDataStr,String prodCode,HttpServletRequest request) throws Exception{
		Page<NlifeCon> page =new Page<NlifeCon>();
		if(StrUtil.isEmpty(jsonDataStr)){
			page.setResult("error");
			page.setMessage("录入共保信息为空，请先添加共保信息后再次保存");
			return page;

		}else if(StrUtil.isEmpty(prodCode)){
			page.setResult("error");
			page.setMessage("产品代码参数为空，请稍后重试");
			return page;
		}
		List<NlifeCon> ls = new ArrayList<NlifeCon>();
		List temls = JsonUtils.parseJson(jsonDataStr, List.class);
		for(int i=0;i<temls.size();i++){
			if(StrUtil.isNotEmpty(temls.get(i).toString())){
				NlifeCon nocar = new NlifeCon();
				logger.info("JsonString" +temls.get(i).toString());
				nocar = JsonUtils.parseJson(temls.get(i).toString(), NlifeCon.class);
				ls.add(nocar);
			}
		}
		// check business rules begin
		if(ls.size()<2){
			page.setResult("error");
			page.setMessage("录入的共保信息记录数至少为2条");
			return page;
		}
		BigDecimal temConPropPercent= BigDecimal.valueOf(0.000000);
		int temMainConFlagCount = 0;
		NlifeCon temCheckConInsu = new NlifeCon();
		NlifeCon nextCheckConInsu = new NlifeCon();
		for(int i = 0;i<ls.size();i++){
			temCheckConInsu = ls.get(i);//获取当前对象
			//1.check 主共保标识
			if("1".equals(temCheckConInsu.getCHIEFFLAG())){
				temMainConFlagCount = temMainConFlagCount+1;
			}
			for(int j = i+1;j<ls.size();j++){
				nextCheckConInsu = ls.get(j);
				if(StrUtil.isNotEmpty(temCheckConInsu.getCOMPANYCODE()) && StrUtil.isNotEmpty(nextCheckConInsu.getCOMPANYCODE())){
					if(temCheckConInsu.getCOMPANYCODE().equals(nextCheckConInsu.getCOMPANYCODE())){
						page.setResult("error");
						page.setMessage("同一产品中同一共保人最多配置一条记录，共保人名称:["+temCheckConInsu.getCOMPANYNAME()+"]重复，请检查");
						return page;
					}
				}else{
					page.setResult("error");
					page.setMessage("同一产品中同一共保人最多配置一条记录，共保人名称:["+temCheckConInsu.getCOMPANYNAME()+"]公司或者["+nextCheckConInsu.getCOMPANYNAME()+"]公司为空，请检查");
					return page;
				}
			}
			if(null!=temCheckConInsu.getCONRATE()){
				temConPropPercent = temConPropPercent.add(temCheckConInsu.getCONRATE().divide(percentHun).setScale(6, BigDecimal.ROUND_HALF_UP));
			}else{
				page.setResult("error");
				page.setMessage("共保人名称:["+temCheckConInsu.getCOMPANYNAME()+"]的共保比例不能为空,请检查");
				return page;
			}
		}
		if(1!=temMainConFlagCount){
			page.setResult("error");
			page.setMessage("同一产品有且只能有一个首席标识为是的记录,请检查");
			return page;
		}
		if(0 != conPropPercent.compareTo(temConPropPercent)){
			page.setResult("error");
			page.setMessage("同一产品所有记录共保比例之和必须等于100");
			return page;
		}
		// check business rules end
		GatewayUser user =  (GatewayUser) request.getSession().getAttribute(Constants.SESSION_USER);
		//1.delet
		nProductService.deleteProdConInsureByProdCode(prodCode);
		//2.save
		BigDecimal realConProp = null;
		for(int i=0;i<ls.size();i++){
			realConProp  = ls.get(i).getCONRATE().divide(percentHun).setScale(6,BigDecimal.ROUND_HALF_UP);
			ls.get(i).setCONRATE(realConProp);
			ls.get(i).setOPERUSER(user.getUserid());
			ls.get(i).setOPERTIME(new Date());
			if("327001".equals(ls.get(i).getCOMPANYCODE())){
				ls.get(i).setCOMPANYTYPE("1");
			}else{
				ls.get(i).setCOMPANYTYPE("3");
			}
			nProductService.saveProdConInsure(ls.get(i));
		}
		List<NlifePlan> tradInsuPlanLists = nlifePlanDao.queryPartnerInfoByProdCode(prodCode);
		if(null!= tradInsuPlanLists && tradInsuPlanLists.size()>0){
			gatewayChannelInfoConfigService.clearAllNewLifeCacheByChannelCodeExtend(tradInsuPlanLists);
		}
		page.setMessage("保存成功");
		return page;
	}


	@RequestMapping(value = "/dowloadProd")
	public void dowloadProd(String productCode,HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception {

		ServletOutputStream outPutStream=null;

		/**浏览器处理*/
		final String userAgent = request.getHeader("USER-AGENT");
		logger.info("使用的浏览器"+userAgent);
		try{
			String  fileName="新意见险产品sql.txt";
			if(userAgent.indexOf( "MSIE")!=-1){
				/**ie浏览器*/
				fileName=java.net.URLEncoder.encode(fileName,"UTF-8");
			}else if(userAgent.indexOf( "Mozilla")!=-1){
				/**火狐浏览器*/
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			}else{
				/**其他浏览器*/
				fileName=java.net.URLEncoder.encode(fileName,"UTF-8");
			}
			String[] product=forProds(productCode);
			System.out.println(product);
			Map<String, Object> map=queryNlife(product);
			/**查询产品信息*/
			response.setContentType("text/plain");
			response.setHeader("Content-disposition","attachment; filename="+fileName);
			outPutStream=response.getOutputStream();
			String ss=FreeMarkerUtil.process("nlifeProd.ftl", map);
			outPutStream.write(ss.getBytes());
			outPutStream.flush();
		}catch(IOException e){
			logger.info("创建文件出错",e);
		}finally{
			if(outPutStream!=null){
				outPutStream.close();
			}
		}
	}

	//	为实现需求:页面中展示详情 新建方法 ->产品信息
	@RequestMapping("/queryProdInfoByCode")
	public @ResponseBody NlifeProd queryProdInfoByCode(String prodCode) throws Exception{
		System.out.println(prodCode);

		NlifeProd lp = INlifeProdDao.queryProdInfoById(prodCode);
		System.out.println("requestMapping中接收到的"+lp.getProdName());
		String date = lp.getStartDate().toString();
		lp.setStringDate(date);
		return lp;
	}
	/**产品导出数据处理
	 * @throws Exception **/
	private Map<String, Object> queryNlife(String[] productCode) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		List<String> prodSqls=new ArrayList<String>();
		List<String> riskSqls=new ArrayList<String>();
		List<String> covSqls=new ArrayList<String>();
		List<String> callSqls=new ArrayList<String>();
		List<String> auwsSqls=new ArrayList<String>();
		List<String> propsSqls=new ArrayList<String>();
		List<String> printsqls=new ArrayList<String>();
		List<String> rationsqls=new ArrayList<String>();
		map.put("prods", productCode);
		/**查询产品*/
		List<Map<String, Object>> prodMap=nProductService.impNlifeProd(map);
		for (Map<String, Object> map2 : prodMap) {
			String sql=getInsertSql(map2, "T_NLIFE_PROD");
			prodSqls.add(sql);
		}
		/**查询险种*/
		List<Map<String, Object>> risks=nProductService.impNlifeRisk(map);
		for (Map<String, Object> map2 : risks) {
			String sql=getInsertSql(map2, "T_NLIFE_RISK");
			riskSqls.add(sql);
		}
		/**查询责任*/
		List<Map<String, Object>> covs=nProductService.impNlifeCov(map);
		for (Map<String, Object> map2 : covs) {
			String sql=getInsertSql(map2, "T_NLIFE_COV");
			covSqls.add(sql);
		}
		/**查询算法*/
		List<Map<String, Object>> calls=tradeFeeCovService.impNlifeCall(map);
		for (Map<String, Object> map2 : calls) {
			String sql=getInsertSql(map2, "T_TRAD_FEE_COV_COMMON");
			callSqls.add(sql);
		}
		/**查询规则*/
		List<Map<String, Object>> auws=feeRateService.impNlifeAuw(map);
		for (Map<String, Object> map2 : auws) {
			String sql=getInsertSql(map2, "T_GATEWAY_AUW_PROD");
			auwsSqls.add(sql);
		}
		/**查询保单配置*/
		List<Map<String, Object>>  props= nProductService.impNlifeProp(map);
		for (Map<String, Object> map2 : props) {
			String sql=getInsertSql(map2, "T_TRAD_PROD_PROP");
			propsSqls.add(sql);
		}
		/**查询回执配置*/
		List<Map<String, Object>> prints=nProductService.impNlifePrint(map);
		for (Map<String, Object> map2 : prints) {
			String sql=getInsertSql(map2, "T_FACADE_PRINT_CONF");
			printsqls.add(sql);
		}
		/**查询保障计划*/
		List<Map<String, Object>> rationMap=nProductService.impNlifeProdRation(map);
		for (Map<String, Object> map2 : rationMap) {
			String sql=getInsertSql(map2, "T_NLIFE_PROD_RATION");
			rationsqls.add(sql);
		}
		map.put("list",prodSqls);
		map.put("risks", riskSqls);
		map.put("covs", covSqls);
		map.put("calls", callSqls);
		map.put("auws", auwsSqls);
		map.put("props", propsSqls);
		map.put("prints", printsqls);
		map.put("rations", rationsqls);
		return map;
	}
	/**产品号处理*/
	private String[] forProds(String productCode){
		if(StrUtil.isEmpty(productCode)){
			return null;
		}
		String[] strs=productCode.split(",");
		return strs;
	}
	/**循环map返回insert语句**/
	private String getInsertSql(Map<String, Object> map,String table){
		String sql="INSERT INTO " +table;
		String cloum=" (";
		String value=" (";
		if(map!=null){
			for (String key : map.keySet()) {
				if(key.equalsIgnoreCase("prod_code")||key.equalsIgnoreCase("trad_prod_code")){
					continue;
				}
				if(key.equalsIgnoreCase("prodCode")){
					cloum+="PROD_CODE,";
					value+="'"+map.get(key)+"',";
					continue;
				}
				if(key.equalsIgnoreCase("auw_prodCode")){
					cloum+="TRAD_PROD_CODE,";
					value+="'"+map.get(key)+"',";
					continue;
				}
			/*	if(key.equalsIgnoreCase("config_id")){
					cloum+=key+",";
					value+="(SELECT MAX(CONFIG_ID)+1  from T_GATEWAY_AUW_PROD AUW) ,";
					continue;
				}*/
				if(key.equalsIgnoreCase("id")&&"t_trad_fee_cov_common".equalsIgnoreCase(table)){
					cloum+=key+",";
					value+="TRADEFEECOV_SEQUESCE.NEXTVAL,";
					continue;
				}
				if(key.equalsIgnoreCase("id")){
					cloum+=key+",";
					value+="(SELECT MAX(ID)+1  from "+table+") ,";
					continue;
				}
				if(key.equalsIgnoreCase("start_date")||key.equalsIgnoreCase("oper_time")||key.equalsIgnoreCase("update_time")||key.equalsIgnoreCase("OPRATE_TIME")||key.equalsIgnoreCase("CREATE_DATE")){
					cloum+=key+",";
					value+="SYSDATE,";
					continue;
				}
				cloum+=key+",";
				if(map.get(key)!=null){
					value+="'"+map.get(key)+"',";
				}else{
					value+=map.get(key)+",";
				}

			}
			cloum=cloum.substring(0,cloum.length()-1)+" )";
			value=value.substring(0,value.length()-1)+" )";
		}
		return sql+cloum+" VALUES "+value;
	}

	/**
	 * 新意见险说明文档
	 * @param session
	 * @param response
	 * @param calDefId
	 * @throws Exception
	 */
	@RequestMapping(value = "/calDocDowlaod")
	public  void calDocDowlaod(HttpSession session,HttpServletResponse response,String calDefId) throws Exception{
		File myFile=null;
		ServletOutputStream outPutStream=null;
		InputStream inputStream=null;
		String fileN = "算法说明";
		String root = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		String path = root.substring(0, root.indexOf("WEB-INF"))+"template"+File.separator+"nlifeCalDoc"+File.separator+"nlifeCall.docx";
		try{
			myFile=new File(path);
			if(myFile.exists()){
				String fileName=java.net.URLEncoder.encode(fileN+".doc","UTF-8");
				response.setHeader("Content-disposition","attachment; filename="+ fileName);
				response.setContentType("application/x-download");
				outPutStream=response.getOutputStream();
				inputStream=new  BufferedInputStream(new FileInputStream(myFile));
				byte[] bytes=new byte[10240];
				int len = 0;
				while((len = inputStream.read(bytes)) != -1)
				{
					outPutStream.write(bytes,0,len);
				}
				outPutStream.flush();
			}
		}catch(IOException e){
			logger.info("算法文档不存在",e);
		}finally{
			if(inputStream!=null){
				inputStream.close();
			}
			if(outPutStream!=null){
				outPutStream.close();
			}
		}
	}
	/* 算法配置导出处理 */
	@RequestMapping(value = "/covExcelDownload")
	public void covExcelDownload(String prodCode , HttpServletResponse resp ,HttpServletRequest req) throws Exception{
		iNlifeCovDao.downloadCovExcel(prodCode , resp);
	}

	@RequestMapping(value = "/queryNlifeCovByMap")
	@ResponseBody
	public List<Map<String,Object>> queryNlifeCovByConditionsMap(String prodCode,String riskCode,String calId) throws SQLException{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("calId", calId);
		map.put("prodCode", prodCode);
		map.put("coreRiskCode", riskCode);
		List<NlifeCov> list = iNlifeCovDao.queryNlifeCovByMap(map);
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			NlifeCov cov = (NlifeCov) iterator.next();
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("code", cov.getCoreCovCode());
			map1.put("name", cov.getCovName());
			result.add(map1);
		}
		return result;
	}
	@RequestMapping(value = "/deleteRationInfo")
	@ResponseBody
	public Page<NlifeRation> deleteRationInfo(String prodCode,String rationId)throws Exception{
		Page<NlifeRation> page=new Page<NlifeRation>();
		NlifeRisk risk = new NlifeRisk();
		NlifeRation nlifeRation = new NlifeRation();
		if(StrUtil.isNotEmpty(prodCode)){
			risk.setProdCode(prodCode);
			nlifeRation.setProdCode(prodCode);
		}
		if(StrUtil.isNotEmpty(rationId)){
			risk.setRationId(rationId);
			nlifeRation.setRationId(rationId);
		}
		if(nProductService.queryIsExistRiskPrimaryKeyByParams(risk)){
			page.setResult("error");
			page.setMessage("保障计划已关联条款，请先删除条款");
			return page;
		}
		if(nlifeRationService.deleteRationByParam(nlifeRation)){
			page.setResult("success");
			page.setMessage("删除成功");
			return page;
		}else{
			page.setResult("error");
			page.setMessage("删除失败");
			return page;
		}
	}
	@RequestMapping(value = "/updateRationInfo")
	@ResponseBody
	public void updateRationInfo(NlifeRation nlifeRation)throws Exception{
		nlifeRationService.updateRationInfoByParam(nlifeRation);
	}
	@RequestMapping(value = "/addRationInfo")
	@ResponseBody
	public Page<NlifeRation> addRationInfo(String prodCode,String rations) throws Exception{
		Page<NlifeRation> page = new Page<NlifeRation>();
		if(!StrUtil.isNotEmpty(prodCode)){
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}
		if(!StrUtil.isNotEmpty(rations)){
			page.setMessage("保障计划不能为空");
			page.setResult("error");
			return page;
		}
		JsonObject o = new JsonParser().parse(rations).getAsJsonObject();
		JsonArray jary = o.get("rationList").getAsJsonArray();
		NlifeRation nlifeRation = null;
		for (JsonElement jsonElement : jary) {
			String rationId =jsonElement.getAsJsonObject().get("rationid").getAsString();
			String rationName=jsonElement.getAsJsonObject().get("rationname").getAsString();
			String jobLevel=jsonElement.getAsJsonObject().get("jobLevel").getAsString();
			if(StrUtil.isNotEmpty(rationId) && StrUtil.isNotEmpty(rationName)){
				nlifeRation = new NlifeRation();
				nlifeRation.setRationId(rationId);
				nlifeRation.setRationName(rationName);
				nlifeRation.setProdCode(prodCode);
				nlifeRation.setJobLevel(jobLevel);
				nlifeRationService.addRation(nlifeRation);

			}
		}
		page.setMessage("添加成功");
		return page;
	}
	@RequestMapping(value = "/getSpecialAttr")
	@ResponseBody
	public List<Map<String, Object>> getSpecialAttr(String instCode,ModelMap model,String prodCode) throws Exception{
		List<Map<String, Object>> specialAttrList=new ArrayList<Map<String,Object>>();
		List<DictDto> specialType = DictCache.getDict("special_attr_type"+instCode);
		if (prodCode!=null) {
			Map<String, Object> prodMap = new HashMap<String, Object>();
			NlifeProd nlifeProd = nProductService.queryProdInfoById(prodCode);
			prodMap.put("nlifeProd", new ObjectMapper().writeValueAsString(nlifeProd));
			specialAttrList.add(prodMap);
		}
		if(specialType!=null){
			for (int i = 0; i < specialType.size(); i++) {
				Map<String, Object> dictMap = new HashMap<String, Object>();
				dictMap.put("dict", specialType.get(i));
				if("select".equals(specialType.get(i).getOtherCode())){
					List<DictDto> dics=DictCache.getDict("special_attr_"+specialType.get(i).getCode());
					dictMap.put("dictSelect", dics);
				}
				if ("securityplan".equals(specialType.get(i).getCode())) {
					List<DictDto> securityplan=DictCache.getDict(Constants.DICT_SECURITY_PLAN);
					dictMap.put("securityplan", securityplan);
				}
				specialAttrList.add(dictMap);
			}
		}
		return specialAttrList;
	}

	@RequestMapping(value="/documentDownload" ,  method = RequestMethod.GET)
	public void downloadDocument(HttpServletRequest request , HttpServletResponse response) throws IOException{

		String classPath=this.getClass().getResource("").getPath();
		String path = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/file/algorithmIntroduce.doc").replace("/WEB-INF", "");
		// 以流的形式下载文件
		InputStream inputStream=null;
		OutputStream outputStream =null;
		try {
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			inputStream = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			//清空response
			response.reset();
			//设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("算法说明.doc","UTF-8") +";filename*=UTF-8");
			response.addHeader("Content-Length", "" + file.length());
			outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			outputStream.write(buffer);
			outputStream.flush();
		}catch (Exception e) {
			logger.info(e);
		}finally{
			if(null!=inputStream){
				inputStream.close();
			}
			if(null!=outputStream){
				outputStream.close();
			}
		}
	}

	/**
	 * 存储车加健信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/saveUnionMessageConfig")
	@ResponseBody
	public Page<TradConfig> saveUnionMessageConfig(HttpServletRequest request , HttpServletResponse response ,String planNo,String deptNo,String minSeat,String maxSeat, String natureArray,String planName,String partnerNo,String planType,String agentType,String serviceCode) throws Exception {
		Page<TradConfig> page = new Page<TradConfig>();
		TradConfig config = new TradConfig();
		config.setPlanNo(planNo);
		config.setPlanName(planName);
		config.setMaxSeat(Integer.parseInt(maxSeat));
		config.setMinSeat(Integer.parseInt(minSeat));
		config.setVhlTyp(natureArray);
		config.setDptCde(deptNo);
		config.setPartnerNo(partnerNo);
		config.setPlanType(planType);
		if("6".equals(agentType) || "8".equals(agentType)){
			config.setIsInputPlan("1");
		}else {
			config.setIsInputPlan("0");
		}
		//config.setIsInputPlan("6".equals(agentType)?"1":"0");

		config.setServiceCode(serviceCode);
		//存之前先查一下是否存在 存在的话走update

		Map<String,String> map = new HashMap<String, String>();
		map.put("planNo", planNo);
		map.put("deptCode", deptNo);
		map.put("planType", planType);
		if(tradConfigService.selectUnionMessageConfig(map) != null){
			//走update的逻辑
			boolean rs = tradConfigService.updateUnionMessageConfig(config);
			if(rs){
				page.setResult("success");
				page.setMessage("更新成功 ！");

			}else{
				page.setResult("error");
				page.setMessage("更新失败 ！请联系管理员");
			}

			return page;
		}
		//存入数据库
		logger.info("存储车意联合信息：" + planNo + "-" + deptNo);
		boolean rs = tradConfigService.insertTradConfigNotNull(config);

		if(rs){
			page.setResult("success");
			page.setMessage("存储成功 ！");
		}else{
			page.setResult("error");
			page.setMessage("存储失败 请联系管理员");
		}
		return page;
	}

	/**
	 * 查询车加健信息
	 * @param planNo
	 * @param DeptCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/selectUnionMessageConfig")
	@ResponseBody
	public Page<TradConfig> selectUnionMessageConfig(HttpServletRequest request,HttpServletResponse response ,String planNo,String deptCode,String planType) throws Exception{
		//查询已配置车加健信息，主要应用于回写
		Page<TradConfig> page = new Page<TradConfig>();

		Map<String,String> map = new HashMap<String, String>();
		map.put("planNo", planNo);
		map.put("deptCode", deptCode);
		map.put("planType", planType);
		List<TradConfig> data = new ArrayList<TradConfig>();
		TradConfig config = tradConfigService.selectUnionMessageConfig(map);
		if(config != null){
			data.add(config);
			page.setData(data);
			page.setResult("success");
		}else{
			page.setResult("empty");
		}
		return page;


	}
	public String isInternetClause(String coreRiskCode) throws Exception {
		return nlifeCoreRiskDao.queryCoreRiskById(coreRiskCode).getIsInternetRisk();

	}
	
	// 根据产品导出规则，修改被复制产品的产品号，用于替换插入语句中的产品号
	private String replaceProdCode(String prodCode) {
		StringBuilder prodCodeSb = new StringBuilder(prodCode);
		switch (prodCodeSb.charAt(6)) {
			case '0':
				prodCodeSb.replace(6, 7, "A");
				break;
			case '1':
				prodCodeSb.replace(6, 7, "B");
				break;
			case '2':
				prodCodeSb.replace(6, 7, "C");
				break;
			case '3':
				prodCodeSb.replace(6, 7, "D");
				break;
			case '4':
				prodCodeSb.replace(6, 7, "E");
				break;
			case '5':
				prodCodeSb.replace(6, 7, "F");
				break;
			case '6':
				prodCodeSb.replace(6, 7, "G");
				break;
			case '7':
				prodCodeSb.replace(6, 7, "H");
				break;
			case '8':
				prodCodeSb.replace(6, 7, "I");
				break;
			case '9':
				prodCodeSb.replace(6, 7, "J");
				break;
		}
		return prodCodeSb.toString();
	}
}
